<template>
  <div class="row">
    <div class="col">
      <el-button @click="start" type="primary" size="default">刷新</el-button>
      <el-button @click="click" type="primary">创建团队分组</el-button>
    </div>
    <el-table :data="group" height="68vh" style="width: 100%">
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="ID" label="分组ID"></el-table-column>
      <el-table-column prop="name" label="分组名称"></el-table-column>
      <el-table-column label="操作" class-name="text-right">
        <template #default="scope">
          <el-button size="default" type="danger" @click="del(scope.row.ID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, defineComponent } from "vue";
import {
  asyncadminaddteamusergroup,
  asyncadmindelteamusergroup,
} from "../../../api/index";
import study from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
export default defineComponent({
  name: "Teamusergroup",
  props: ["team", "group", "start"],
  setup(p) {
    const team = computed<study.Iteam>(() => {
      return p.team;
    });
    const group = computed<study.Iteamusergroup[]>(() => {
      return p.group;
    });

    function formatter(updatedAt: string | number | Date) {
      return toLocaleDateString(updatedAt);
    }

    function click() {
      ElMessageBox.prompt("请输入名称", "添加团队分组", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: (msg) => {
          return !group.value.map((v) => v.name).includes(msg);
        },
        inputErrorMessage: "名称重复",
      })
        .then(({ value }) => {
          if (team.value.ID) {
            asyncadminaddteamusergroup({
              teamid: team.value.ID,
              name: value,
              description: "",
            })
              .then((e) => {
                ElMessage.success("添加成功");
                if (p.start) p.start();
              })
              .catch((e) => {
                ElMessage.success("添加失败");
              });
          }
        })
        .catch(() => { });
    }

    async function del(ID: number) {
      ElMessageBox.confirm("确定要删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async () => {
          await asyncadmindelteamusergroup({ ID });
          if (p.start) p.start();
        })
        .catch(() => {
          ElMessage.error("删除失败");
        });
    }

    return {
      formatter,
      click,
      del,
    };
  },
});
</script>
